package com.ciwong.epaper.modules.reciteWords.ui;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.common.db.DatabaseHelper;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.reciteWords.presenter.IReciteWordDetailactivity;
import com.ciwong.epaper.modules.reciteWords.presenter.ReciteWordDetailPresenter;
import com.ciwong.epaper.modules.reciteWords.util.download.DeserializeCallBack;
import com.ciwong.epaper.modules.reciteWords.util.download.DownloadCallBack;
import com.ciwong.epaper.modules.reciteWords.util.download.WordBookDownloadManager;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ImageLoaderHelper;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.File;


public class ReciteWordDetailActivity extends BaseActivity implements IReciteWordDetailactivity, View.OnClickListener {

    private View cv_details, iv_no_data;
    private TextView tv_word, tv_symbol, tv_pretations, tv_esentence, tv_sentence, tv_close_self;
    private ImageView iv_audio_word, iv_pic, iv_audio_sentence;
    private ImageView iv_audio_playing;
    private ReciteWordDetailPresenter reciteWordDetailPresenter;
    private WordDetail wordDetail;
    private Intent intent;
    public static int INTENT_FROM_WORD_LIST_ACTIVITY = 0;
    public static int INTENT_FROM_WORD_STUDY_ACTIVITY = 1;
    private int intFlag;
    private String tittle = "单词详情";
    private String strReturn = "返回";
    private String strGoOn = "继续做题";

    @Override
    protected void preCreate() {
        super.preCreate();
        intent = getIntent();
        intFlag = intent.getIntExtra(IntentFlag.INTENT_FLAG_FORM, 0);
        if (intFlag==INTENT_FROM_WORD_LIST_ACTIVITY){

        } else if (intFlag==INTENT_FROM_WORD_STUDY_ACTIVITY){
            //去除title
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            //去掉Activity上面的状态栏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

    }

    @Override
    protected int setView() {
        return R.layout.activity_recite_word_details;
    }

    @Override
    protected void findViews() {
        iv_no_data = findViewById(R.id.iv_no_data);
        cv_details = findViewById(R.id.cv_details);
        tv_word = findViewById(R.id.tv_word);
        tv_symbol = findViewById(R.id.tv_symbol);
        tv_pretations = findViewById(R.id.tv_pretations);
        tv_esentence = findViewById(R.id.tv_esentence);
        tv_sentence = findViewById(R.id.tv_sentence);
        tv_word = findViewById(R.id.tv_word);
        tv_word = findViewById(R.id.tv_word);
        iv_audio_word = findViewById(R.id.iv_audio_word);
        iv_pic = findViewById(R.id.iv_pic);
        iv_audio_sentence = findViewById(R.id.iv_audio_sentence);
        tv_close_self = findViewById(R.id.tv_close_self);
        iv_audio_word.setOnClickListener(this);
        iv_audio_sentence.setOnClickListener(this);
        tv_close_self.setOnClickListener(this);
        audioStopAnimation(iv_audio_word);
        audioStopAnimation(iv_audio_sentence);
    }

    @Override
    protected void initEvent() {
        showData();
    }

    @Override
    protected void init() {
        setTitleText(tittle);
        if (intFlag == INTENT_FROM_WORD_LIST_ACTIVITY) {
            tv_close_self.setText(strReturn);
        } else if (intFlag == INTENT_FROM_WORD_STUDY_ACTIVITY) {
            hideTitleBar();
            tv_close_self.setText(strGoOn);
        }

    }


    @Override
    protected void loadData() {

    }


    private void showData() {
        String bookId = intent.getStringExtra(IntentFlag.INTENT_FLAG_RECITE_VERSION);
        String did = intent.getStringExtra(IntentFlag.INTENT_FLAG_RECITE_INTERATION_ID);
        reciteWordDetailPresenter = new ReciteWordDetailPresenter(getBaseContext(), this);
        reciteWordDetailPresenter.queryDataFromDB(bookId, did);
    }
    long lastTime=0;
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_audio_word) {
            if (iv_audio_playing != null)
                audioStopAnimation(iv_audio_playing);
            iv_audio_playing = iv_audio_word;
            if (reciteWordDetailPresenter != null && wordDetail != null){

                if (doubleClick(lastTime))return;
                if (!NetworkUtils.isOnline()){
                    ToastUtil.INSTANCE.toastCenterNoNetError();
                    return;
                }
                reciteWordDetailPresenter.startPlay(wordDetail.getWordFile());
            }


        } else if (v.getId() == R.id.iv_audio_sentence) {
            if (iv_audio_playing != null)
                audioStopAnimation(iv_audio_playing);
            iv_audio_playing = iv_audio_sentence;
            if (reciteWordDetailPresenter != null && wordDetail != null){
                if (doubleClick(lastTime))return;
                if (!NetworkUtils.isOnline()){
                    ToastUtil.INSTANCE.toastCenterNoNetError();
                    return;
                }
                reciteWordDetailPresenter.startPlay(wordDetail.getSentFile());
            }

        } else if (v.getId() == R.id.tv_close_self) {
            finish();
        }

    }

    private boolean doubleClick(long lastTime) {
        long DURATION=800;//两次点击间隔时间
        long nowTime = System.currentTimeMillis();
        long clickDuration = nowTime - lastTime;
        this.lastTime=nowTime;
        if (clickDuration<DURATION){//间隔时间短（连击了）
            return true;
        } else{
            return false;
        }
    }

    private void audioStopAnimation(ImageView imageView) {
        Drawable drawable = imageView.getDrawable();
        if (drawable != null && drawable instanceof AnimationDrawable) {
            ((AnimationDrawable) drawable).selectDrawable(0);
            ((AnimationDrawable) drawable).stop();
        }
    }

    private void audioPlayAnimation(ImageView imageView) {
        imageView.setVisibility(View.VISIBLE);
        Drawable drawable = imageView.getDrawable();
        if (drawable != null && drawable instanceof AnimationDrawable) {
            ((AnimationDrawable) drawable).start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (reciteWordDetailPresenter != null)
            reciteWordDetailPresenter.stopPlay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        setResult(RESULT_OK);
    }

    @Override
    public void onQueryReult(WordDetail wordDetail) {
        this.wordDetail = wordDetail;
        if (wordDetail == null) {
            iv_no_data.setVisibility(View.VISIBLE);
            cv_details.setVisibility(View.GONE);
            return;
        }
        iv_no_data.setVisibility(View.GONE);
        cv_details.setVisibility(View.VISIBLE);

        String wordFile = wordDetail.getWordFile();
        String sentFile = wordDetail.getSentFile();
        if (TextUtils.isEmpty(wordFile))
            iv_audio_word.setVisibility(View.GONE);
        else
            iv_audio_word.setVisibility(View.VISIBLE);
        if (TextUtils.isEmpty(sentFile))
            iv_audio_sentence.setVisibility(View.GONE);
        else
            iv_audio_sentence.setVisibility(View.VISIBLE);

        if (TextUtils.isEmpty(wordDetail.getWordPic())) {
            iv_pic.setVisibility(View.GONE);
        } else {
            iv_pic.setVisibility(View.VISIBLE);
            ImageLoaderHelper.getInstance().init(getApplicationContext());
            ImageLoader.getInstance().displayImage(wordDetail.getWordPic(),
                    iv_pic, new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String s, View view) {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {
                            iv_pic.setVisibility(View.GONE);
                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {

                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {

                        }
                    });
        }
        tv_word.setText(wordDetail.getWords());

        String symbol = wordDetail.getSymbol();
        if (symbol != null) {
            //去除重音符号
            if(symbol.contains("'")) {
                String symHandled="";//处理后的音标
                String[] split = symbol.split("'");
                for (int i=0;i<split.length;i++){
                    symHandled+= split[i];
                }
                symbol=symHandled;
            }
            if (!symbol.startsWith("[")) {
                symbol = "[" + symbol;
            }
            if (!symbol.endsWith("]")) {
                symbol += "]";
            }
            tv_symbol.setText(symbol);
        }

        tv_pretations.setText(wordDetail.getPretations());

        String textSentences = wordDetail.getSentences();
        if (!TextUtils.isEmpty(textSentences)) {
            String replaceTxt = textSentences.replace("\r", "\n");
            tv_esentence.setVisibility(View.VISIBLE);
            tv_sentence.setVisibility(View.VISIBLE);
            tv_sentence.setText(replaceTxt);
            if (TextUtils.isEmpty(replaceTxt)||(replaceTxt.length()<=1&&replaceTxt.equals("."))) {
//            tv_sentence.setText("─");
                tv_esentence.setVisibility(View.GONE);
                tv_sentence.setVisibility(View.GONE);
            }
        }
    }


    @Override
    public void onStartPlay(Object mp3) {
        Log.e(TAG, "播放音频onStartPlay: ");
        if (iv_audio_playing != null)
            audioPlayAnimation(iv_audio_playing);
    }

    @Override
    public void onStopPlay(Object mp3) {
        Log.e(TAG, "播放音频onStopPlay: ");
        if (iv_audio_playing != null)
            audioStopAnimation(iv_audio_playing);
    }

    @Override
    public void onPlayError(int errorCode, Object tag) {
        Log.e(TAG, "播放音频onStopPlay: ");
        if (iv_audio_playing != null)
            audioStopAnimation(iv_audio_playing);
    }
}
